import AddJoint from './addJoint'
const { ccclass, property } = cc._decorator;

@ccclass
export default class Input extends cc.Component {

    @property(cc.Prefab)
    linePrefab: cc.Prefab = null

    @property(cc.Prefab)
    wheel: cc.Prefab = null

    @property(cc.Graphics)
    linePhysics: cc.Graphics = null

    linePhysicsOriginPos: cc.Vec2
    startPoint: cc.Vec2
    endPoint: cc.Vec2

    @property(cc.Node)
    Car: cc.Node = null

    @property(cc.Node)
    Camera: cc.Node = null

    recordPos: cc.Vec2
    currentPos: cc.Vec2

    onLoad() {
        var manager = cc.director.getPhysicsManager();
        manager.enabled = true;
        manager.debugDrawFlags = 0;
    }

    start() {
        this.init()

        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStartCallback, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMoveCallback, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEndCallback, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchEndCallback, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this);
    }

    init() {
        this.linePhysicsOriginPos = this.linePhysics.node.position
    }

    onKeyUp(e) {
        // console.log(e);
        if (e.keyCode == 32) {

        }
    }

    onTouchStartCallback(event) {
        for (let i of this.Car.children) {
            i.destroy()
        }
        this.Car.position = this.Camera.position
        this.linePhysics.clear()
        let pos = this.node.convertToNodeSpaceAR(event.getLocation());
        this.linePhysics.moveTo(pos.x, pos.y);  //把路径移动到画布中的指定点，不创建线条
        this.recordPos = cc.v2(pos.x, pos.y);
        this.startPoint = pos
    }

    onTouchMoveCallback(event) {
        let pos = this.node.convertToNodeSpaceAR(event.getLocation());
        this.linePhysics.lineTo(pos.x, pos.y);      //添加一个新点，然后在画布中创建从该点到最后指定点的线条
        this.linePhysics.stroke();
        this.linePhysics.moveTo(pos.x, pos.y);

        // 记录当前手移动到的点
        this.currentPos = cc.v2(pos.x, pos.y);

        //求两点之间的距离
        let subVec = this.currentPos.subSelf(this.recordPos);  //向量减法
        let distance = subVec.mag() + 2;
        // 如果距离大于一定值，这里的5是预制体的width
        if (distance >= 12) {
            // 给定方向向量
            let tempVec = cc.v2(0, 1);
            // 求两点的方向角度
            let rotateVec = subVec.signAngle(tempVec) / Math.PI * 180 - 90;
            // 创建预制体
            let lineItem = cc.instantiate(this.linePrefab);
            lineItem.angle = -rotateVec;

            //设置父对象
            lineItem.parent = this.Car;

            // 这一步是为了防止两个线段之间出现空隙，动态改变预制体的长度
            lineItem.setPosition(pos.x, pos.y);
            lineItem.width = distance + 2;
            // lineItem.getComponent(cc.PhysicsBoxCollider).offset.x = -lineItem.width / 2

            lineItem.getComponent(cc.PhysicsBoxCollider).size.width = lineItem.width;

            //设置weld关节
            let curIndex = AddJoint.contactCar(this.Car)
            // console.log(curIndex)
            //设置关节连接
            if (curIndex != 0) {
                // console.log('连接关节，当前index ： ', curIndex)

                let preNode = this.Car.children[curIndex - 1]


                //设置距离关节
                preNode.addComponent(cc.DistanceJoint).connectedBody = lineItem.getComponent(cc.RigidBody)
                preNode.getComponent(cc.DistanceJoint).distance = preNode.position.sub(lineItem.position).mag();
                preNode.getComponent(cc.DistanceJoint).frequency = 0
                preNode.getComponent(cc.DistanceJoint).apply()

                // //设置棱柱组件
                // preNode.addComponent(cc.PrismaticJoint).connectedBody = lineItem.getComponent(cc.RigidBody)
                // preNode.getComponent(cc.PrismaticJoint).enableLimit = true
                // preNode.getComponent(cc.PrismaticJoint).anchor = cc.v2(0, 0)
                // preNode.getComponent(cc.PrismaticJoint).connectedAnchor = cc.v2(0, 0)
                // preNode.getComponent(cc.PrismaticJoint).referenceAngle = AddJoint.calcAngle(preNode, lineItem)
                // let dis = preNode.position.sub(lineItem.position).mag();
                // preNode.getComponent(cc.PrismaticJoint).lowerLimit = dis
                // preNode.getComponent(cc.PrismaticJoint).upperLimit = dis
                // preNode.getComponent(cc.PrismaticJoint).apply()

                //设置焊接组件
                preNode.addComponent(cc.WeldJoint).connectedBody = lineItem.getComponent(cc.RigidBody)
                let widthLast = preNode.width / 2
                preNode.getComponent(cc.RigidBody).type = cc.RigidBodyType.Static
                preNode.getComponent(cc.WeldJoint).anchor = cc.v2(widthLast - 1, 0)
                preNode.getComponent(cc.WeldJoint).connectedAnchor = cc.v2(-widthLast + 1, 0)
                preNode.getComponent(cc.WeldJoint).referenceAngle = AddJoint.calcAngle(preNode, lineItem)
                preNode.getComponent(cc.WeldJoint).frequency = 0
                preNode.getComponent(cc.WeldJoint)[0] = 0
                preNode.getComponent(cc.WeldJoint).apply()




            }
            //

            lineItem.getComponent(cc.PhysicsBoxCollider).apply();
            // 将此时的触摸点设为记录点
            this.recordPos = cc.v2(pos.x, pos.y);
        }
    }

    onTouchEndCallback(event) {
        for (let i of this.Car.children) {
            i.getComponent(cc.RigidBody).type = cc.RigidBodyType.Dynamic
            i.getComponent(cc.PhysicsBoxCollider).offset = cc.v2(0, 0)
            i.getComponent(cc.PhysicsBoxCollider).apply()
        }
        let wheel1 = cc.instantiate(this.wheel)
        wheel1.parent = this.Car
        wheel1.setPosition(this.startPoint)
        wheel1.getComponent(cc.WheelJoint).connectedBody = this.Car.children[0].getComponent(cc.RigidBody)
        wheel1.getComponent(cc.WheelJoint).anchor = cc.v2(0, 0)
        wheel1.getComponent(cc.WheelJoint).connectedAnchor = cc.v2(-this.Car.children[0].width / 2, 0)
        wheel1.getComponent(cc.WheelJoint).motorSpeed = -1200

        let lastLine = this.Car.children[this.Car.children.length - 2]
        this.endPoint = lastLine.position
        let wheel2 = cc.instantiate(this.wheel)
        wheel2.parent = this.Car
        wheel2.setPosition(this.endPoint)
        wheel2.getComponent(cc.WheelJoint).connectedBody = lastLine.getComponent(cc.RigidBody)
        wheel2.getComponent(cc.WheelJoint).anchor = cc.v2(0, 0)
        wheel2.getComponent(cc.WheelJoint).connectedAnchor = cc.v2(lastLine.width / 2, 0)
        wheel2.getComponent(cc.WheelJoint).motorSpeed = -1200
        let dis = this.startPoint.sub(this.endPoint).mag();
        wheel1.addComponent(cc.DistanceJoint).connectedBody = wheel2.getComponent(cc.RigidBody)
        wheel1.getComponent(cc.DistanceJoint).distance = dis
        // wheel1.getComponent(cc.DistanceJoint).apply()


        // // 分段纠正
        // let count = this.Car.children.length
        // let i = 0
        // let j = count - 1
        // for (let pices = 0; pices < Math.floor((count - 1) / 2); pices += 2) {
        //     AddJoint.addDistanceJoint(this.Car.children[i], this.Car.children[j])
        //     i++
        //     j--
        // }
    }

    onDestroy() {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStartCallback, this);
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMoveCallback, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.onTouchEndCallback, this);
    }

}
